<template>
  <a-form-model ref="form" :label-col="labelCol" :wrapper-col="wrapperCol">
    <a-row style="margin-top: 10px">
      <a-col :span="12">
        <a-form-model-item :label = "i18n('pane.title','标题行')" prop = "title" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number  :min="0" id="title" v-model="titleLine" />
        </a-form-model-item>
      </a-col>
      <a-col :span="12">
        <a-form-model-item :label = "i18n('pane.content','内容行')" prop = "content" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input-number :min="0" id="content" v-model="content" />
        </a-form-model-item>
      </a-col>


    </a-row>
    <a-row>
      <a-col :span="12">
        <a-form-model-item :label = "i18n('pane.type','类型')" prop = "type" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-radio-group v-model="type">
            <a-radio :value="1">
              {{i18n('pane.database','数据库')}}
            </a-radio>
          </a-radio-group>
          <rx-button style="margin: 3px 0 0 10px"  :butnIcon="'reload'" :show-no-right="true" @click="refresh()">{{i18n('pane.reload','重新加载标题行')}}</rx-button>

        </a-form-model-item>
      </a-col>
      <a-col :span="12">

      </a-col>
    </a-row>
    <a-row>

      <a-col :span="12" v-if= "content!='' || titleLine != ''">
        <a-form-model-item  :label = "i18n('pane.datasource','数据源')"  :labelCol="labelCol" :wrapperCol="wrapperCol">
          <rx-input-button ref="dsName" v-model="dsName" @click="openDataSource" style="width: 100%;"></rx-input-button>
        </a-form-model-item>
      </a-col>
      <a-col :span="12" v-if= "content!='' || titleLine != ''">
        <a-form-model-item  :label = "i18n('pane.selTable','选择表')"  :labelCol="labelCol" :wrapperCol="wrapperCol">
          <rx-input-button ref="tableName" v-model="tableName"  @click="onTableMap" style="width: 100%;"></rx-input-button>
        </a-form-model-item>
      </a-col>

    </a-row>
    <a-row>
      <a-col :span="24">
        <a-form-model-item :labelCol="{span:3}" :wrapperCol="{span:21}" :label="i18n('pane.selTable','目标表映射')">
          <div >
            <rx-grid
              ref="table"
              :showPage="false"
              :dataSource="fields"
              :columns="dataGridColumn"
              :enableHtmlEscape="false"
              :heightAuto="true"
            >
            <span slot="columnType" slot-scope="{text,record}">
                <span v-html="renderDataType(record)"></span>
            </span>
              <span slot="isNull" slot-scope="{text,record}">
                {{getIsNullFilter(text)}}
            </span>
              <span slot="mapType" slot-scope="{text,record,index,blur}">
                <a-select labelInValue :options="mapTypes" v-model="record.mapType"
                          @blur="blur(index,'mapType',text,record)"></a-select>
            </span>
              <span slot="mapValue" slot-scope="{text,record,index,blur}">
                <a-select v-if="record.mapType=='field' || record.mapType.key=='field'" :options="fieldDatas" v-model="record.mapValue"
                          @blur="blur(index,'mapValue',text,record)"></a-select>
                <a-input v-if="record.mapType=='fixValue' || record.mapType.key=='fixValue'" v-model="record.mapValue"
                         @blur="blur(index,'mapValue',text,record)"/>
                <rx-input-button v-if="record.mapType=='scriptValue' || record.mapType.key=='scriptValue'" @click="openScript($event,blur,index,record)"
                                 v-model="record.mapValue"></rx-input-button>
                <rx-input-button v-if="record.mapType=='seqValue' || record.mapType.key=='seqValue'" @click="openSeqId($event,blur,index,record)"
                                 v-model="record.mapValue"></rx-input-button>
            </span>
            </rx-grid>
          </div>
        </a-form-model-item>
      </a-col>
    </a-row>
  </a-form-model>

</template>

<script>
  import FormDbApi from "@/api/form/bo/formDb"
  import {RxDialog,Dialog, RxInputButton, Util,RxFit,BaseFormModel,JsConstant} from "@lowcode/jpaas-common-lib"
  import ImportScript from "./ImportScript"
  import AppName from "@/assets/js/AppName.js";

  export default {
    name: "ImportExcelPane",
    props: ["field","title","conf"],
    mixins:[AppName],
    components: {
      RxDialog,
      RxInputButton
    },
    computed: {
      table() {
        return this.$refs.table;
      },
    },
    data: function () {
      return {
        labelCol: {span: 6},
        wrapperCol: {span: 18},
        labelCol1: {span: 3},
        wrapperCol1: {span: 19},
        mdl: {
          operator: 'new'
        },
        titleLine: "",
        content: "",
        condition: "",
        filterSql: "",
        type: 1,
        dsName:"",
        tableName:"",
        headerContent:[],
        operatorOptions: [
          {label: this.$ti18('rxList.add','新增'), value: 'new'},
          {label: this.$ti18('rxList.update','更新'), value: 'upd'},
          {label: this.$ti18('rxList.delBtn','删除'), value: 'del'}
        ],
        fields: [],
        dataGridColumn: [
          {
            title: this.$ti18('rxList.index','序号'),
            type: 'indexColumn',
            width: 100,
            dataIndex: 'serial',
            scopedSlots: {customRender: 'serial'}
          },
          {title: this.i18n('pane.field','字段'), dataIndex: 'fieldName', width: 100},
          {title: this.i18n('form.remarks','备注'), dataIndex: 'comment', width: 100},
          {title: this.i18n('pane.dateType','数据类型'), dataIndex: 'columnType', width: 100, scopedSlots: {customRender: 'columnType'}},
          {title: this.i18n('pane.isNull','是否可空'), dataIndex: 'isNull', width: 100, scopedSlots: {customRender: 'isNull'}},
          {
            title: this.i18n('pane.valueSource','值来源'),
            dataIndex: 'mapType',
            displayField: 'mapTypeName',
            allowCellEdit: true,
            width: 100,
            scopedSlots: {customRender: 'mapType'}
          },
          {title: this.i18n('pane.value','值'), dataIndex: 'mapValue', allowCellEdit: true, width: 100, scopedSlots: {customRender: 'mapValue'}}
        ],
        mapTypes: [{value: 'none', label: this.i18n('pane.none','无')},
          {value: 'field', label: this.i18n('pane.formExcel','从EXCEL字段获取')},
          {value: 'fixValue', label: this.i18n('pane.fixValue','固定值')},
          {value: 'scriptValue', label: this.i18n('pane.scriptValue','从脚本函数计算获取')},
          {value: 'pkId', label: this.i18n('pane.pkId','由系统产生的主键字段值')},
          {value: 'time', label: this.i18n('pane.time','系统时间')},
          {value: 'curUserId', label: this.i18n('pane.curUserId','获取当前用户Id')},
          {value: 'curUserName', label: this.i18n('pane.curUserName','获取当前用户姓名')},
          {value: 'batId', label: this.i18n('pane.batId','批次ID')}],
        fieldDatas: [],
      }
    },
    created() {
      this.loadData();
    },
    methods: {
      i18n(name,text,key){
        return this.$ti18(name,text,"ImportExcel",key);
      },
      getIsNullFilter(isNull) {
          const isNullMap = {
              true: this.i18n('pane.yes','是'),
              false: this.i18n('pane.no','否')
          }
          return isNullMap[isNull]
      },
      renderDataType(record) {
        var val = record.columnType;
        if (val == "varchar") {
          return val + "(" + record.charLen + ")";
        } else if (val == "number") {
          if (record.decimalLen == 0) {
            return val + "(" + record.intLen + ")";
          } else {
            return val + "(" + record.intLen + "," + record.decimalLen + ")"
          }
        }
        return val;
      },


      loadData() {
        Object.assign(this.mdl, this.conf);
        if (this.conf && this.conf.gridData) {
          this.titleLine = this.conf.titleLine;
          this.dsName = this.conf.dsName;
          this.content = this.conf.content;
          this.tableName =  this.conf.tableName,
          this.type = this.conf.type;
          this.headerContent = this.conf.headerContent ;
          this.fields = this.conf.gridData;
        } else {
          if(this.conf == undefined ||( this.conf.dsName == undefined && this.conf.tableName == undefined )){
            return;
          }
          FormDbApi.getByName("dsName=" + this.conf.dsName + "&tbName=" + this.conf.tableName).then(data => {
            var list = data.columnList;
            this.fields = this.parseFields(list);
          })
        }
        delete this.mdl.gridData;
      },
      parseFields(list){
        for(var i=0;i<list.length;i++){
          list[i].mapType='';
          list[i].mapValue='';
        }
        return list;
      },
      getData() {
        return {
          ...this.mdl,
          title: this.title,
          titleLine: this.titleLine,
          content: this.content,
          dsName: this.dsName,
          tableName: this.tableName,
          type: this.type,
          headerContent: this.headerContent,
          gridData: this.table.getData()
        }
      },
      openSeqId(vm, blur, index, record) {
        Dialog.openSysSeqIdDialog({
          curVm: this, widthHeight: ['1300px', '600px']
        }, function (self, data) {
          vm.setVal(data.alias, data.name);
          record.mapValue = data.alias;
          blur(index, 'mapValue', data.alias, record)
        })
      },
      openScript(vm, blur, index, record) {
        var self = this;
        var baseConf = {
          "curVm": self,
          component: ImportScript,
          title: self.$ti18('pane.scriptTitle','设置字段映射',"ImportExcel"),
          widthHeight: ['1200px', '700px'],
          data: {
            value: record.mapValue,
            fieldName: record.fieldName,
            headerContent: self.headerContent,
          }
        };
        Util.open(baseConf, function (action, data) {
          if (action ==  'ok') {
            record.mapValue = data;
          }
          blur(index, 'mapValue', data, record)
        });
      },

      openDataSource(vm) {
        Dialog.openDataSourceDialog({
          curVm: this, widthHeight: ['1200px', '600px'],
          data:{appName: this.serviceName}
        }, function (self, data) {
            if(!data){
                return;
            }
          vm.setVal(data.alias, data.name)
        })
      },

      onTableMap(vm) {
        var self_ = this;
        var datasource;
        if(this.dsName != ""){
          datasource = JSON.parse(this.dsName).value;
        }
        else{
          datasource = this.dsName;
        }
        Dialog.openTableQueryDialog({
          curVm: this, widthHeight: ['1200px', '600px'], data: {ds: datasource}
        }, function (self, data) {
            if(!data){
                return;
            }
          self_.isSelectTable = "2";
          vm.setVal(data.tableName, data.tableName)
          self_.conf =  {dsName: datasource ,tableName:  data.tableName};
          if(self_.titleLine > self_.field.length || self_.titleLine < 0){
              self_.$message.error(self_.$ti18('msa.onTableTips','标题行设置有误，请检查并重新选择表',"ImportExcel"));
          }
          self_.setFieldData(self_.titleLine);
          self_.loadData();
        })
      },

      setFieldData(titleLine) {
        let header = this.field[titleLine - 1];
        if(header) {
            this.headerContent = header;
            for (var i = 0; i < header.length; i++) {
                var temp = {};
                temp.label = header[i];
                temp.value = header[i];
                this.fieldDatas[i] = temp;
            }
        }else {
            this.headerContent = [];
            this.fieldDatas = [];
        }
      },
      refresh(){
        this.setFieldData(this.titleLine);
      }
    },

    watch:{
      "titleLine"(val){
        this.content = this.titleLine + 1;
      },

    }
  }
</script>

<style scoped>

</style>